const config = require('../config/config.js')
const db  = require('mysql')


db_config = db.createPool({
    host     : config.mysql.host,
    port     : config.mysql.port,
    user     : config.mysql.username,
    password : config.mysql.password,
    database : config.mysql.dbname
})
/**
 * 
 * @param sql 接收的sql语句
 * @param values 接受的参数： 为数组
 */
/*
const query = function( sql, values ) {
    return new Promise(( resolve, reject ) => {
        pool.getConnection(function(err, connection) {
            if (err) {
                console.log(err)
                resolve( err )
            } else {
                connection.query(sql, values, ( err, rows) => {
                    if ( err ) {
                        reject( err )
                    } else {
                        resolve( rows )
                    }
                    connection.release()
                })
            }
        })
    })
}*/


class mysql {

    //连接池实现
    static getInstance(){
        if(!mysql.instance) mysql.instance = new mysql()
        return mysql.instance
    }
    constructor(){
        console.log('触发构造函数')
        this.conn = this.connect()
    }
    
    connect(){
        /*
        return new Promise(( resolve, reject ) => {
            pool.getConnection(function(err, connection) {
                if(err) reject(err)
                else    console.log('mysql链接成功!')
                resolve(connection)
            })
        })*/
        return db.createConnection(db_config);
    }

    find(sql='', params={}){
        //console.log('查找')
        //console.log(this.conn)
        this.conn.query(sql, params, function(err,result){
            //this.conn.release();
            if(err) throw err;
            console.log(result);
            //console.log(result.affectedRows);
        });

    }

}
module.exports = new mysql()
